<?php
App::uses('AppController', 'Controller');

/**
 * Images Controller
 *
 * @property Image $Image
 */
class ImagesController extends AppController {
	public function beforeFilter() {
		parent::beforeFilter();
	}
	
	public function admin_index($item_id = null){
		$conditions = array();
		if(isset($item_id) && $item_id > 0)
			$conditions['Item.id'] = $item_id;
			
		$items = $this->Image->Item->find('all', array(
			'fields' => array('Item.id', 'Item.name'),
			'conditions' => $conditions,
			'order' => array('Item.created' => 'DESC')
		));
		$this->set('items', $items);
		$this->set('item_id', $item_id);
	}
	
	public function ajax_index($item_id = null){
		// if item_id param appears, will select only in those ID
		// otherwise select from all categories and albums
		$conditions = array();
		if(isset($item_id) && $item_id > 0)
			$conditions['Image.item_id'] = $item_id;
		
		$this->paginate = array(
			'recursive' => 0,
			'conditions' => $conditions,
			'limit' => 10,
			'order' => array('Image.created' => 'DESC')
		);
		$this->set('images', $this->paginate());
	}
	
	public function api_add(){
		$item_id = $this->request->data['Image']['item_id'];
		if(!empty($this->request->data['Attach'])){
			$photos = $this->request->data['Attach'];
			$count = 0;
			foreach($photos as $photo){
				list($url1, $url2) = split("\|", $photo, 2);
				$this->Image->create();
				if($this->Image->save(array(
					'item_id' => $item_id,
					'url1' => $url1,
					'url2' => $url2)))
					$count ++;
			}
			$error = 0;
			$message = $count.' images have been saved.';
		}
		else{
			$error = -1;
			$message = 'The images could not be saved.';
		}
		$this->set('error', $error);
		$this->set('data', $message);
	}
	
	public function api_delete($id = null) {
		$error = -1;
		$this->Image->id = $id;
		if (!$this->Image->exists()) {
			$message = 'Invalid image';
		}
		if ($this->Image->delete()) {
			$error = 0;
			$message = 'Image deleted';
		}
		else{
			$error = 1;
			$message = 'Image was not deleted';			
		}
		$this->set('error', $error);
		$this->set('data', $message);
	}
	
	public function api_status($id = null){
		$error = -1;
		$this->Image->id = $id;
		if (!$this->Image->exists()) {
			$message = 'Invalid image';
		}
		else{		
			if($this->Image->updateAll(
			array('Image.status' => '1 - Image.status', 'modified' => 'NOW()'),
			array('Image.id' => $id))){
				$error = 0;
				$message = 'Status has been changed';
			}
			else{
				$error = 1;
				$message = 'Status could not be changed';					
			}
		}
		$this->set('error', $error);
		$this->set('data', $message);		
	}

	public $components = array('Resize');
	public function ajax_upload(){
		if(!empty($this->request->data['Upload'])){ 
			$images = $this->request->data['Upload'];
			$upload = array();
			foreach ($images as $i => $image){
				if(!empty($image['tmp_name']) && is_uploaded_file($image['tmp_name'])){
					$fileName = md5(time().$image['name']).'.'.$this->getFileExtension($image['name']);
					CakeLog::write('debug', 'uploaded ' . $fileName);
					
					if(move_uploaded_file($image['tmp_name'], IMAGES.'uploads'.DS.$fileName)){
						CakeLog::write('debug', 'copied to ' . IMAGES.'uploads'.DS.$fileName);
						$url1 = $this->Resize->resize($fileName, 75, 75, 50, 1, 'thumbs');
						$url2 = $this->Resize->resize($fileName, 640, 640, 100, 0, 'fulls');
						
						$upload[$i]['url1'] = $url1;
						$upload[$i]['url2'] = $url2;				 
					}
				}	
			}
			$this->set('images', $upload);
		}
	}
	
	public function ajax_fbalbum_index(){
		require_once (APP . 'Vendor' . DS . 'facebook/FacebookSdk.php');
		$config = array();
		$config['appId'] = Configure::read("Facebook.AppId");
		$config['secret'] = Configure::read("Facebook.Secret");

		$facebook = new FacebookSdk($config);
		//Create Query
		$params = array(
	        'method' => 'fql.query',
	        'query' => "SELECT object_id, name FROM album WHERE owner = ".Configure::read("Facebook.ShopId")." ORDER BY created DESC",
	    );
		try{
			$albums = $facebook->api($params);
			$this->set('albums', $albums);
		} catch(FacebookApiException $e){
			$this->log("Facebook: " . $e->getMessage());
			$this->set('albums', null);
		}		
	}
	
	public function ajax_fbalbum_view(){
		$album_id = $_GET['album_id'];
				
		require_once (APP . 'Vendor' . DS . 'facebook/FacebookSdk.php');
		$config = array();
		$config['appId'] = Configure::read("Facebook.AppId");
		$config['secret'] = Configure::read("Facebook.Secret");

		$facebook = new FacebookSdk($config);
		//Create Query
		$params = array(
	        'method' => 'fql.query',
	        'query' => "SELECT object_id, images FROM photo WHERE album_object_id = ".$album_id." ORDER BY created DESC",
	    );
		try{
			$photos = $facebook->api($params);
			$this->set('photos', $photos);
		} catch(FacebookApiException $e){
			$this->log("Facebook: " . $e->getMessage());
			$this->set('photos', null);
		}		
	}	
}